#include "Enemy.h"
#include "RootScene.h"

CEnemy* CreateEnemy( CCLayer* pLayer, CCPoint oLocation, float fDelay )
{
	CEnemy* pEnemy = new CEnemy();

	if( pEnemy )
	{
		CCSprite* pSprite = CCSprite::create( "enemy.png" );
		pEnemy->addChild( pSprite, 1, 0 );
		pEnemy->setHP_Max( 100 );
		pEnemy->setHP_Cur( 100 );
		pEnemy->setMoveSpeed( 0.5f );

		pLayer->addChild( pEnemy );
		pEnemy->setPosition( oLocation );
		pEnemy->scheduleUpdate();
		pEnemy->scheduleOnce(schedule_selector(CEnemy::doActivate), fDelay);
		pEnemy->setTargetPoint( oLocation );
	}
	return pEnemy;
}

CEnemy::CEnemy(void)
{
	mActive = false;
}

CEnemy::~CEnemy(void)
{
}

void CEnemy::doActivate( float dt )
{
	mActive = true;
}

void CEnemy::update( float dt )
{
	if (!mActive)
	{
		return;
	}

	CRootScene* pScene = (CRootScene*)getParent();
	if( !pScene )
		return;

	const CCPoint& mCurrentPositon = getPosition();

	if ( ccpDistance( mCurrentPositon, mTargetPoint ) < 2 )
	{
		if( !pScene->getNextWalkTarget( mTargetPoint ) )
		{
			CCNode* pParent = getParent();
			pParent->removeChild( this, true );
			release();
			return;
		}
	}

	CCPoint direction( ccpNormalize( ccpSub( mTargetPoint, mCurrentPositon ) ) );
	
	CCSprite* pSprite = (CCSprite*)getChildByTag(0);
	pSprite->setRotation(CC_RADIANS_TO_DEGREES(atan2(direction.y, - direction.x)));
	setPosition( ccpAdd( mCurrentPositon, ccpMult( direction, getMoveSpeed() ) ) );
}

void CEnemy::draw( void )
{
	const int hp_board_width_offset = -10;
	const int hp_board_width = 20;
	const int hp_board_height_offset = 16;
	const int hp_board_height = 2;
	CCPoint healthBarBack[] = {
		ccp( hp_board_width_offset, hp_board_height_offset),
		ccp( hp_board_width_offset + hp_board_width, hp_board_height_offset),
		ccp( hp_board_width_offset, hp_board_height_offset - hp_board_height ),
		ccp( hp_board_width_offset + hp_board_width, hp_board_height_offset - hp_board_height )
	};
	ccDrawSolidPoly(healthBarBack, 4, ccc4f(255, 0, 0, 255));

	CCPoint healthBar[] = {
		ccp(hp_board_width_offset, hp_board_height_offset),
		ccp(hp_board_width_offset + (float)(mHP_Cur * hp_board_width) / mHP_Max, hp_board_height_offset),
		ccp(hp_board_width_offset + (float)(mHP_Cur * hp_board_width) / mHP_Max, hp_board_height_offset - hp_board_height),
		ccp(hp_board_width_offset, hp_board_height_offset - hp_board_height)
	};
	ccDrawSolidPoly(healthBar, 4, ccc4f(0, 255, 0, 255));

	CCNode::draw();
}
